<template>
  <div class="padding flex direction-column height-100 bg-white position-relative">
    <div class="tree-box dark-alpha-block" ref="drag-zoom">
      <vue-drag-zoom
        :area-node="node"
        allow-zoom
        :range="0.2"
        :max-zoom="1.2"
        :min-zoom="0.2"
      >
        <vue-org-tree
          :data="treeData" :render-content="renderContent" :horizontal="horizontal"
          @on-node-click="onNodeClick"
        ></vue-org-tree>
      </vue-drag-zoom>
    </div>
    <data-detail v-if="indicatorCode" ref="detail" :indicator-code="indicatorCode"></data-detail>
  </div>
</template>

<script>
import VueDragZoom from '@/components/vue-drag-zoom'
import VueOrgTree from 'vue2-org-tree'
import 'vue2-org-tree/dist/style.css'
import { selectPointList } from '@/api/point'
import { selectIndicatorList } from '@/api/indicator'
import DataDetail from '@/views/energy-use-model/data-detail'

const api = {
  queryWorkShop: selectPointList,
  queryMonitorPoint: selectIndicatorList,
}

export default {
  name: 'energy-use-model',
  components: {
    VueOrgTree,
    VueDragZoom,
    DataDetail,
  },
  data () {
    return {
      node: null,
      horizontal: false,
      indicatorCode: '',
      treeRoot: {},
      treeData: {},
    }
  },
  mounted () {
    this.node = this.$refs['drag-zoom']
    this.reload()
  },
  methods: {
    reload () {
      this.queryWorkShop().then(data => {
        data = Array.isArray(data) ? data[0] : {}
        const { children, ...rest } = data
        this.treeRoot = { ...rest }
        const codes = (children || []).map(v => v.pointCode)

        if (codes.length > 0) {
          this.treeData = {
            ...this.treeRoot,
          }
          this.queryMonitorPoint(codes).then((points) => {
            this.makeTreeData(children, points)
          })
        }
      }).catch(() => {})
    },
    renderContent (h, data) {
      // eslint-disable-next-line
      const horizontal = this.horizontal
      const isTreeRoot = this.isTreeRoot(data)
      const isWorkShop = this.isWorkShop(data)
      const isMonitorPoint = this.isMonitorPoint(data)
      if (isTreeRoot || isWorkShop) {
        return h('span', {
          style: `
            display: inline-block;
            width: ${(horizontal || isTreeRoot) ? 'auto' : '15px'};
            white-spacing: ${horizontal ? 'nowrap' : 'normal'};
            word-wrap: break-word;
          `,
        }, data.pointName)
      }

      const render = (name, value) => h(
        'li',
        {
          style: `
            list-style: none;
            padding: 5px 0;
            font-size: 12px;
            white-space: nowrap;
          `
        },
        [
          h('label', {
            style: `
              color: var(--text-color-regular, #999);
            `
          }, name + '：'),
          h('span', value),
        ]
      )
      if (isMonitorPoint) {
        return h(
          'el-popover',
          {
            props: {
              trigger: 'hover',
              placement: 'right',
            }
          },
          [
            h('ul', {
              style: `
                list-style: none;
                text-align: left;
                padding-left: 0;
                margin: 0;
              `,
            }, [
              render('监测点名称', data.indicatorName),
              render('监测点编码', data.indicatorCode),
              render('监测点类型', data.type)
            ]),
            h('div', {
              slot: 'reference',
              style: `
                width: ${horizontal ? 'auto' : '15px'};
                text-orientation: mixed;
                word-wrap: break-word;
                white-spacing: ${horizontal ? 'nowrap' : 'normal'}
              `,
            }, [
              h('span', {}, data.indicatorName),
            ])
          ]
        )
      }
    },
    makeTreeData (workShopData, monitorPoints) {
      const children = [...workShopData]
      children.forEach(v => {
        const pointCode = v.pointCode
        const target = monitorPoints.find(vv => vv.pointCode === pointCode)
        if (target) {
          v.children = [...target.list]
        }
      })
      this.treeData = {
        ...this.treeData,
        children,
      }
    },
    // 获取车间（点位)
    queryWorkShop () {
      return new Promise((resolve, reject) => {
        api.queryWorkShop().then(res => {
          if (res.code === 200) {
            res.data.forEach(v => {
              v.label = v.pointName
            })
            resolve(res.data)
          } else {
            reject(new Error(res.code))
          }
        })
      })
    },
    // 获取测点（指标）
    queryMonitorPoint (codes) {
      return new Promise((resolve, reject) => {
        api.queryMonitorPoint(codes).then(res => {
          if (res.code === 200) {
            resolve(res.data)
          } else {
            reject(new Error(res.code))
          }
        })
      })
    },
    isTreeRoot (node) {
      const treeRoot = this.treeRoot
      const pointTree = node.pointTree || ''
      return !!((treeRoot && node.pointCode === treeRoot.pointCode) || (pointTree && pointTree.length === 1))
    },
    isWorkShop (node) {
      const pointTree = (node.pointTree || '').split(',')
      return (!this.isTreeRoot(node)) && pointTree.length === 2
    },
    isMonitorPoint (node) {
      return !!node.indicatorCode
    },

    onNodeClick (e, data) {
      if (this.isMonitorPoint(data)) {
        this.indicatorCode = data.indicatorCode
        this.$nextTick(() => {
          this.$refs.detail.open()
        })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.tree-box {
  width: 100%;
  height: 100%;
  flex: 1;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
